const express = require("express");
const router = express.Router();
const Money = require("../../models/Money");
const User = require("../../models/User");
var ObjectID = require("mongodb").ObjectID;
const passport = require("passport");

router.post("/add", (req, res) => {
  const type = new Money({
    user_id: req.body.user_id,
    money: req.body.money,
    name: req.body.name,
  });
  type
    .save()
    .then((user) =>
      User.update(
        {
          _id: req.body.user_id,
        },
        {
          money: req.body.money,
        }
      ).then((money) => {
        res.json({
          success: true,
          msg: "充值成功",
        });
      })
    )
    .catch((err) => console.log(err));
});

router.get(
  "/getList",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Money.aggregate(
      [
        {
          $lookup: {
            from: "users",
            localField: "user_id",
            foreignField: "_id",
            as: "users",
          },
        },
        {
          $unwind: {
            // 拆分子数组
            path: "$users",
            preserveNullAndEmptyArrays: true, // 空的数组也拆分
          },
        },
        {
          $project: {
            _id: 1,
            name: 1,
            money: 1,
            users: 1,
            date: 1,
          },
        },
      ],
      (err, docs) => {
        if (err) {
          return console.log(err);
        }
        docs.forEach((element) => {
          if (element.users && element.users.name) {
            element.user_name = element.users.name;
          }

          delete element.users;
        });
        res.json({
          success: true,
          result: docs,
        });
      }
    );
  }
);

module.exports = router;
